import puppeteer, { type Browser, type Page } from 'puppeteer-core'
import config from '@main/config'

export default class Puppeteer {
  #browser: Browser | null = null
  #page: Page | null = null

  constructor() {
    this.#setBroswer().then(this.#setPage)
  }

  async #setBroswer() {
    this.#browser = await puppeteer.launch({
      executablePath: config.chromePath
    })
  }

  async getBroswer() {
    if (!this.#browser) {
      await this.#setBroswer()
    }

    return this.#browser!
  }

  async #setPage() {
    if (!this.#page) {
      const browser = await this.getBroswer()

      this.#page = await browser.newPage()
      await this.#page.setJavaScriptEnabled(true)
      await this.#page.setViewport({ width: 1920, height: 1080 })
    }
  }

  async getPage() {
    if (!this.#page) {
      await this.#setPage()
    }

    return this.#page!
  }

  async gotoUtilIdel(url: string) {
    const page = await this.getPage()
    await page.goto(url, { waitUntil: 'networkidle0' })
    return page
  }
}
